<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible" width="60%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="140px">
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input v-model="dataForm.newsTitle" placeholder="新闻标题"></el-input>
      </el-form-item>
      <el-form-item label="新闻图片" prop="newsImg">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.newsImg" :src="dataForm.newsImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="新闻外链地址" prop="newsTitle">
        <el-input v-model="dataForm.links" placeholder="新闻外链地址"></el-input>
      </el-form-item>
      <el-form-item label="新闻简介" prop="newsTitle">
        <el-input  type="textarea" v-model="dataForm.newsDesc" placeholder="新闻简介"></el-input>
      </el-form-item>
      <el-form-item label="新闻内容" prop="newsContent">
        <editor :init="editorInit" v-model="dataForm.newsContent"/>
      </el-form-item>
      <el-form-item label="新闻状态" prop="state">
        <el-select v-model="dataForm.state" placeholder="请选择">
          <el-option
            v-for="item in stateTypes"
            :key="item.label"
            :label="item.label"
            :value="item.type">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="新闻类型" prop="newsPro">
        <el-select v-model="dataForm.newsPro" placeholder="请选择">
          <el-option
            v-for="item in newsProTypes"
            :key="item.label"
            :label="item.label"
            :value="item.type">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否置顶" prop="newsPro">
        <el-select v-model="dataForm.top" placeholder="请选择">
          <el-option
            v-for="item in topTypes"
            :key="item.label"
            :label="item.label"
            :value="item.type">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" prop="createDate">
        <el-date-picker
          v-model="dataForm.createDate"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .webDesc .el-form-item__content {
    line-height: 10px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .myclass {
     width: 60%;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import Editor from '@tinymce/tinymce-vue'
  import API from '@/api'
  import axios from 'axios'
  import requestUrl from '../../../src/api/requestUrl'
  export default {
    components: { Editor },
    data () {
      return {
        visible: false,
        url: '',
        stateTypes: [{
          type: 'Y',
          label: '有效'
        }, {
          type: 'N',
          label: '无效'
        }],
        topTypes: [{
          type: 0,
          label: '不置顶'
        }, {
          type: 1,
          label: '置顶'
        }],
        newsProTypes: [{
          type: 'N',
          label: '新闻'
        }, {
          type: 'P',
          label: '通告'
        }],
        dataForm: {
          id: 0,
          newsTitle: '',
          newsImg: '',
          links: '',
          newsDesc: '',
          newsContent: '',
          state: 'Y',
          newsPro: 'N',
          createDate: '',
          top: 0,
          uid: '',
          uname: ''
        },
        editorInit: {
          language: 'zh_CN',
          convert_urls: false,
          plugins: [
            'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
          ],
          toolbar: [
            'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
            'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
          ],
          images_upload_handler: function (blobInfo, success, failure) {
            let formdata = new FormData()
            formdata.set('file', blobInfo.blob())
            axios.post(requestUrl('/sys/oss/imgUpload'), formdata).then(res => {
              success(res.data.url)
            }).catch(res => {
              failure('error')
            })
          }
        },
        dataRule: {
          newsTitle: [
            { required: true, message: '新闻标题不能为空', trigger: 'blur' }
          ],
          newsImg: [
            { required: true, message: '新闻图片不能为空', trigger: 'blur' }
          ],
          newsDesc: [
            { required: true, message: '新闻简介不能为空', trigger: 'blur' }
          ],
          state: [
            { required: true, message: '新闻状态不能为空', trigger: 'blur' }
          ],
          newsPro: [
            { required: true, message: '新闻类型不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    activated  () {
      this.weblog()
    },
    methods: {
      init (id) {
        this.url = API.oss.upload(this.$cookie.get('token'))
        console.log(this.url)
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            API.baseworknews.info(this.dataForm.id).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.newsTitle = data.baseworknews.newsTitle
                this.dataForm.newsImg = data.baseworknews.newsImg
                this.dataForm.newsDesc = data.baseworknews.newsDesc
                this.dataForm.links = data.baseworknews.links
                this.dataForm.newsContent = data.baseworknews.newsContent
                this.dataForm.state = data.baseworknews.state
                this.dataForm.newsPro = data.baseworknews.newsPro
                this.dataForm.createDate = data.baseworknews.createDate
                this.dataForm.uid = data.baseworknews.uid
                this.dataForm.top = data.baseworknews.top
                this.dataForm.uname = data.baseworknews.uname
              }
            })
          }
        })
      },
      weblog (id) {
        this.url = API.oss.upload(this.$cookie.get('token'))
        console.log(this.url)
      },
      handleAvatarSuccess (res, file) {
        //    this.dataForm.webLogo = URL.createObjectURL(file.raw)
        this.dataForm.newsImg = res.url
      },
      beforeAvatarUpload (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/x-icon' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            var params = {
              'id': this.dataForm.id || undefined,
              'newsTitle': this.dataForm.newsTitle,
              'newsImg': this.dataForm.newsImg,
              'newsContent': this.dataForm.newsContent,
              'newsDesc': this.dataForm.newsDesc,
              'links': this.dataForm.links,
              'top': this.dataForm.top,
              'state': this.dataForm.state,
              'newsPro': this.dataForm.newsPro,
              'createDate': this.dataForm.createDate,
              'uid': this.dataForm.uid,
              'uname': this.dataForm.uname
            }
            console.log(params.createDate)
            var tick = !this.dataForm.id ? API.baseworknews.add(params) : API.baseworknews.update(params)
            tick.then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
